package com.jshan.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.jshan.base.entity.SysUser;
import com.jshan.service.SysUserService;
import com.jshan.base.vo.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import com.jshan.common.annotation.OperationLog;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

import java.util.List;

@Tag(name = "认证相关接口")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Slf4j
public class AuthController {

    private final SysUserService userService;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    @OperationLog("用户登录")
    public Result login(@RequestBody SysUser loginUser) {
        Result result = userService.login(loginUser);
        log.info("登录结果: {}", result);
        return result;
    }

    @Operation(summary = "用户登出")
    @PostMapping("/logout")
    @OperationLog("用户登出")
    public Result logout() {
        log.info("用户 {} 尝试退出登录", StpUtil.getLoginIdDefaultNull());
        StpUtil.logout();
        return Result.ok();
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/info")
    @OperationLog("获取用户信息")
    public Result getUserInfo() {
        try {
            Long userId = StpUtil.getLoginIdAsLong();
            log.info("尝试获取用户 {} 的信息", userId);
            Result userInfo = userService.getUserInfo();
            log.info("获取用户信息结果: {}", userInfo);
            return userInfo;
        } catch (Exception e) {
            log.error("获取用户信息失败: {}", e.getMessage(), e);
            return Result.fail("获取用户信息失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取用户权限")
    @GetMapping("/permissions")
    @OperationLog("获取用户权限")
    public Result<List<String>> getPermissions() {
        try {
            // 获取当前登录用户的权限列表
            List<String> permissions = StpUtil.getPermissionList();
            log.info("获取用户 {} 的权限列表: {}", StpUtil.getLoginIdDefaultNull(), permissions);
            return Result.ok(permissions);
        } catch (Exception e) {
            log.error("获取用户权限失败: {}", e.getMessage(), e);
            return Result.fail("获取用户权限失败: " + e.getMessage());
        }
    }
}
